package com.grm.security.login;

import com.alibaba.fastjson.JSON;
import com.grm.common.Result;
import com.grm.util.JwtUtil;
import com.grm.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登录成功处理程序
 *
 * @author gaorimao
 * @date 2022-02-04
 */
@Slf4j
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        // 返回token给前台
        String username = authentication.getName();
        String token = jwtUtil.createToken(username);
        // 存入redis并设置7天有效期
        redisUtil.set("token:" + username, token, 60 * 60 * 24 * 7);
        Result result = Result.success("登录成功！", token);
        String jsonResult = JSON.toJSONString(result);
        PrintWriter out = response.getWriter();
        out.write(jsonResult);
        out.flush();
        out.close();
    }
}
